<template>
  <div class="app-container">
    <h1 id="dingdan">订单查询
      <el-link type="primary" style="font-size: 16px" @click="initData">点击刷新</el-link>
    </h1>
    <el-form :inline="true" size="mini" style="text-align: right;border: 0.5px #99a9bf solid;padding: inherit">
      <el-row>
        <el-col :span="6">
          <el-form-item label="桌号">
            <el-input v-model="search.locationId" placeholder="桌号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="1">
          <el-form-item label="是否支付">
            <el-col :span="12">
              <el-select v-model="search.isPaid" placeholder="是否支付">
                <el-option label="全部" :value="2"></el-option>
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </el-col>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="1">
          <el-form-item label="是否有效">
            <el-col :span="12">
              <el-select v-model="search.isInvalid" placeholder="是否有效">
                <el-option label="全部" :value="2"></el-option>
                <el-option label="是" :value="0"></el-option>
                <el-option label="否" :value="1"></el-option>
              </el-select>
            </el-col>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row>
        <el-col :span="6">
          <el-form-item label="菜品名">
            <el-input v-model="search.name" placeholder="菜品名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="起止时间">
            <el-date-picker
              v-model="search.date"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4" :offset="2">
          <el-form-item>
            <el-button type="primary" @click="dataSearch">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="margin-top: 25px"></div>
    <el-row type="flex" class="row-bg" justify="start">
      <el-col :span="2">
        <el-popconfirm
          title="确定作废吗？"
          @onConfirm="orderListSelectedInvalid">
          <el-button slot="reference" type="danger" size="mini">作废</el-button>
        </el-popconfirm>
      </el-col>
    </el-row>
    <div style="margin-top: 25px"></div>

    <el-table
      ref="orderListTable"
      v-loading="dataLoading"
      :data="data"
      element-loading-text="加载中"
      border
      fit
      stripe
      highlight-current-row>
      <el-table-column
        align="center"
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column label="编号" align="center" width="50">
        <template scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="时间" align="center" width="200">
        <template scope="scope">
          {{ new Date(Date.parse(scope.row.date)).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column label="餐桌号" align="center" prop="locationId">
      </el-table-column>
      <el-table-column label="支付状态" align="center">
        <template scope="scope">
          {{ scope.row.isPaid| isPaidFilter }}
        </template>
      </el-table-column>

      <el-table-column label="是否有效" align="center">
        <template scope="scope">
          {{ scope.row.isInvalid| isInvalidFilter }}
        </template>
      </el-table-column>

      <el-table-column label="总价（元）" align="center" prop="sum">
      </el-table-column>
      <el-table-column label="人数" align="center" prop="peopleSum">
      </el-table-column>


      <el-table-column label="订单详情" align="center" width="210">
        <template scope="scope">
          <el-link type="primary" @click="showOrderDetail(scope.row)">详情</el-link>
          <br/>
          <el-link type="primary" @click="orderDetailPrint(scope.row)">打印</el-link>
          <br/>
          <el-popconfirm
            title="确定作废吗？"
            @onConfirm="orderListinvalid(scope.row)">
            <el-link slot="reference" type="danger">作废</el-link>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-backtop :bottom="100">
    </el-backtop>
    <el-dialog
      title="订单详情"
      style="text-align: center"
      :visible.sync="orderDialogVisible"
      width="20%">
      <div ref="orderDetailPrint">
        <p style="font-weight: bolder;font-size: 18px">餐桌号：{{ currentLocationId }}号</p>
        <div style="line-height: 30px;font-size: 14px">
          <li v-for="k in currentOrderDetails" :key="k.id"
              style="font-size: 16px">
            <span style="font-weight: bolder">{{ k.foodDetail ? k.foodDetail.name : '' }}</span>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <span>{{ k.foodDetail ? ('￥' + k.foodDetail.price + '×' + k.number) : '' }}</span>
          </li>
          <p style="font-size: 14px;line-height: 14px">备注:{{ this.currentOrderList.note }}</p>
          <p style="font-size: 20px;font-weight: bolder;margin-top: 10px;text-align: right;margin-right: 18%">
            总价：<span style="color: green">{{ currentOrderDetails|sumPrice }}</span>
          </p>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="orderDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
import request from "@/utils/request";
import Event from "@/utils/event-bus";

export default {
  name: "index",
  data() {
    return {
      dataLoading: true,
      data: [],
      search: {
        locationId: '',
        isPaid: 0,
        isInvalid: 0,
        date: [],
        name: ''
      },
      currentOrderDetails: [],
      currentLocationId: 0,
      orderDialogVisible: false,
      currentOrderList: {}
    }
  },
  filters: {
    isPaidFilter(k) {
      return {
        0: '未支付',
        1: '已支付'
      }[k]
    },
    isInvalidFilter(k) {
      return {
        0: '有效',
        1: '无效'
      }[k]
    },
    sumPrice(orderDetails) {
      let sum = 0;
      orderDetails.forEach(v => {
        sum = sum + v.foodDetail.price * v.number
      })
      return sum + '元'
    }
  },
  created() {
    Event.$on('reflush_order', () => {
      this.initData()
    });
    this.initData()
    this.timer = setInterval(() => {
      // this.initData()
    }, 5000)
  },
  destroyed() {
    clearInterval(this.timer)
  },
  methods: {
    initData() {
      this.dataLoading = true
      const date = new Date()
      const month = (date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : '0' + parseInt(date.getMonth() + 1)
      const day = date.getDate() >= 10 ? date.getDate() : '0' + parseInt(date.getDate())
      request({
        url: '/order/shop',
        params: {
          shopId: this.$store.state.user.shop.id,
          dateStart: `${date.getFullYear()}-${month}-${day}T00:00:00.00`,
          dateEnd: `${date.getFullYear()}-${month}-${day}T23:59:59.999999`,
          //是否支付（0：未支付，1：已支付）
          isPaid: 0,
          //是否无效（0：有效，1：无效）
          isInvalid: 0
        },
      }).then(v => {
        this.data = v.data
      }).finally(() => {
        this.dataLoading = false
      })
    },
    showOrderDetail(order) {
      this.dataLoading = true
      request({
        url: `/order/${order.id}`,
      }).then(v => {
        this.currentOrderDetails = v.data
        this.currentLocationId = order.locationId
        this.currentOrderList = order
      }).finally(() => {
        this.orderDialogVisible = true
        this.dataLoading = false
      })
    },
    dataSearch() {
      this.dataLoading = true
      request({
        url: '/order/shop',
        params: Object.assign({...this.search}, {
          shopId: this.$store.state.user.shop.id,
          dateStart: this.search.date[0] && this.search.date[0].toISOString(),
          dateEnd: this.search.date[1] && this.search.date[1].toISOString(),
          //重要！！禁止清除
          date: '',
          isInvalid: this.search.isInvalid === 2 ? null : this.search.isInvalid,
          isPaid: this.search.isPaid === 2 ? null : this.search.isPaid
        }),
      }).then(v => {
        this.data = v.data
      }).finally(() => {
        this.dataLoading = false
      })
    },
    orderDetailPrint(order) {
      this.dataLoading = true
      request({
        url: `/order/${order.id}`,
      }).then(v => {
        const currentOrderDetails = v.data
        let lis = ''
        currentOrderDetails.forEach(k => {
          lis = lis + `<li style="font-size: 16px">
            <span style="font-weight: bolder">${k.foodDetail ? k.foodDetail.name : ''}</span>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <span>${k.foodDetail ? ('￥' + k.foodDetail.price + '×' + k.number) : ''}</span>
          </li>`
        })

        const printStr = `<div ref="orderDetailPrint" style="width: 50%">
       <p style="font-weight: bolder;font-size: 18px;text-align: center;line-height: 12px">${this.$store.state.user.shop.name}</p>
        <p style="font-weight: bolder;font-size: 12px;text-align: right;line-height: 12px">餐桌号：${order.locationId}号</p>
        <p style="font-size: 10px;line-height: 12px">※※※※※※※※※※※※※※※※※※※※</p>
        <div style="line-height: 30px;font-size: 14px">
        ${lis}
        <p style="font-size: 12px;line-height: 14px">备注:${order.note}</p>
        <hr />

          <p style="font-size: 20px;font-weight: bolder;margin-top: 10px;text-align: left;
          margin-left: 45%">
            总价：<span style="color: green">${order.sum}元</span>
          </p>
        </div>
      </div>`
        const newWin = window.open(window.document.URL) //将打印的部分赋值给新打开的标签页
        newWin.document.body.innerHTML = printStr;
        newWin.print();//执行打印
        newWin.close();//关闭打印窗口
      }).finally(() => {
        this.dataLoading = false
      })


    },
    orderListinvalid(orderList) {
      request({
        url: `/order/${orderList.id}`,
        method: 'POST',
        data: {
          id: orderList.id,
          isInvalid: 1
        },
      }).then(v => {
        this.$message({
          type: 'success',
          center: true,
          message: '作废成功！',
          duration: 1500
        });
        this.dataSearch()
      }).finally(() => {
      })
    },
    orderListSelectedInvalid() {
      this.$refs.orderListTable.selection.forEach(v => {
        request({
          url: `/order/${v.id}`,
          method: 'POST',
          data: {
            id: v.id,
            isInvalid: 1
          },
        }).then(v => {
        }).finally(() => {
        })
      })
      this.$message({
        type: 'success',
        center: true,
        message: `作废成功 ${this.$refs.orderListTable.selection.length}个！`,
        duration: 1500
      });
      this.initData()
    }
  }
}
</script>

<style scoped>

</style>
